package com.vanke.kotlin.domain

import com.vanke.kotlin.data.server.ForecastServer
import com.vanke.kotlin.db.ForecastDb

/**
 * @name Kotlin
 * @package name：com.vanke.kotlin.domain
 * @class describe
 * @anthor shiyuchuan
 * @time 2017/7/31 15:25
 */
class ForecastProvider(val sources: List<ForecastDataSource>
                       = ForecastProvider.SOURCES)
{

    companion object {
        val DAY_IN_MILLIS = 1000 * 60 * 60 * 24
        val SOURCES = listOf(ForecastDb(), ForecastServer())
    }

    fun requestByZipCode(zipCode: Long, days: Int): ForecastList =
            requestToSource{
        val res =it.requestForecastByZipCode(zipCode,todayTimeSpan())
        if (res !=null && res.size() >=days) res else null
    }

    fun requestForecast(id: Long): Forecast = requestToSource { it.requestDayForecast(id) }

    private fun  todayTimeSpan(): Long
            = System.currentTimeMillis() / DAY_IN_MILLIS * DAY_IN_MILLIS

    private fun <T: Any> requestToSource(
            f: (ForecastDataSource) -> T?
    ): T = sources.firstResult{f(it)}

}
